<?php 
 
namespace app\common\model;

use app\common\model\BaseModel;
use app\common\traits\ModelTrait;
use app\common\utils\JsonService;
use think\facade\Db;

/**
* This is the model class for table "{ptf_goods}".
*
* @property int $goods_id 商品id 
* @property int $cat_id 分类id 
* @property string $goods_sn 商品编号
* @property string $goods_name 商品名称
* @property int $click_count 点击数 
* @property int $brand_id 品牌id 
* @property int $store_count 库存数量 
* @property int $comment_count 商品评论数 
* @property int $weight 商品重量克为单位 
* @property int $market_price 市场价 
* @property int $shop_price 本店价 
* @property int $cost_price 商品成本价 
* @property string $price_ladder 价格阶梯
* @property string $keywords 商品关键词
* @property string $goods_remark 商品简单描述
* @property string $goods_content 商品详细描述
* @property string $original_img 商品上传原始图
* @property int $is_real 是否为实物 
* @property int $is_on_sale 是否上架 
* @property int $is_free_shipping 是否包邮0否1是 
* @property int $on_time 商品上架时间 
* @property int $sort 商品排序 
* @property int $is_recommend 是否推荐 
* @property int $is_new 是否新品 
* @property int $is_hot 是否热卖 
* @property int $last_update 最后更新时间 
* @property int $goods_type 商品所属类型id，取值表goods_type的id 
* @property int $spec_type 商品规格类型，取值表spec的id 
* @property int $give_integral 购买商品赠送积分 
* @property int $exchange_integral 积分兑换：0不参与积分兑换，积分和现金的兑换比例见后台配置 
* @property int $suppliers_id 供货商ID 
* @property int $sales_sum 商品销量 
* @property string $shipping_area_ids 配送物流shipping_area_id,以逗号分隔
*/
class Goods extends BaseModel{

    protected $pk = 'goods_id';
    protected $name = 'goods';

    use ModelTrait;
    protected $autoWriteTimestamp = true;
    //protected $dateFormat = 'Y-m-d';
    protected $createTime = 'create_time';
    protected $updateTime = 'update_time';

    /**
    * {@inheritdoc}
    */
    public function attributeLabels()
    {
        return [
            'goods_id' => '商品id',
            'cat_id' => '分类id',
            'goods_sn' => '商品编号',
            'goods_name' => '商品名称',
            'click_count' => '点击数',
            'brand_id' => '品牌id',
            'store_count' => '库存数量',
            'comment_count' => '商品评论数',
            'weight' => '商品重量克为单位',
            'market_price' => '市场价',
            'shop_price' => '本店价',
            'cost_price' => '商品成本价',
            'price_ladder' => '价格阶梯',
            'keywords' => '商品关键词',
            'goods_remark' => '商品简单描述',
            'goods_content' => '商品详细描述',
            'original_img' => '商品上传原始图',
            'is_real' => '是否为实物',
            'is_on_sale' => '是否上架',
            'is_free_shipping' => '是否包邮0否1是',
            'on_time' => '商品上架时间',
            'sort' => '商品排序',
            'is_recommend' => '是否推荐',
            'is_new' => '是否新品',
            'is_hot' => '是否热卖',
            'last_update' => '最后更新时间',
            'goods_type' => '商品所属类型id，取值表goods_type的id',
            'spec_type' => '商品规格类型，取值表spec的id',
            'give_integral' => '购买商品赠送积分',
            'exchange_integral' => '积分兑换：0不参与积分兑换，积分和现金的兑换比例见后台配置',
            'suppliers_id' => '供货商ID',
            'sales_sum' => '商品销量',
            'shipping_area_ids' => '配送物流shipping_area_id,以逗号分隔',
        ];
    }

    //获取推荐商品
    public static function getRecommendGoods($where=['is_on_sale'=>1],$limit = 6){
        $goods = self::getAll($where,['goods_id'=>'desc'],'goods_id,goods_name,shop_price,original_img,goods_type,sales_sum,comment_count',$limit)->each(function($item2){
            if($item2['goods_type'] !=0){
                $min = SpecGoodsPrice::where(['goods_id'=>$item2['goods_id']])->min('price');
                $max = SpecGoodsPrice::where(['goods_id'=>$item2['goods_id']])->max('price');
                //$item2['shop_price'] = $min.'-'.$max;
            }
        });
        return $goods;
    }

    //关联获取店铺
    public function getShop(){
        return $this->hasOne('Shop','shop_id','shop_id')->field('shop_id,shop_name,shop_type_name,shop_group_name,company_name,province_id,city_id,district_id,address_detail');
    }


    /**
     * 获取商品规格
     * @param $goods_id|商品id
     * @return array
     */
    public static function get_spec($goods_id)
    {
        //商品规格 价钱 库存表 找出 所有 规格项id
        $keys = SpecGoodsPrice::field("GROUP_CONCAT(`key` ORDER BY store_count desc SEPARATOR '_') as keys2")->where(["goods_id"=>$goods_id])->find()->toArray();

        $keys = $keys['keys2'];
        $filter_spec = array();
        if ($keys) {
            $keys = str_replace('_', ',', $keys);
            //$sql = "SELECT a.name,a.order,b.* FROM __PREFIX__spec AS a INNER JOIN __PREFIX__spec_item AS b ON a.id = b.spec_id WHERE b.id IN($keys) ORDER BY b.id";
            $model = new Spec();
            $filter_spec2 = Spec::alias('a')->field('a.name,a.order,b.*')->join('spec_item b','a.id=b.spec_id')->where([['b.id','in',$keys]])->order('b.id asc')->select()->toArray();
            //$filter_spec2 = Db::query($sql);

            foreach ($filter_spec2 as $key => $val) {
                $filter_spec[$val['name']][] = array(
                    'item_id' => $val['id'],
                    'item' => $val['item'],
                );
            }
        }
        return $filter_spec;
    }


    /*
     * 根据商品重量计算物流运费
     */
    public static function getFreight($member_id,$address_id,$shipping_code,$weight){

        $postFee = 0;
        //计算物流信息
        $user_address = MemberAddress::getOne(["address_id"=>$address_id],'province');
        $address = ShippingArea::where(['shipping_id'=>$shipping_code])->column('shipping_area_id');

        $shipping_area_id = AreaRegion::where([['shipping_area_id','in',$address],['region_id','=',$user_address['province']]])->column('shipping_area_id');

        // 省份找不到 找默认配置全国的物流费
        if ($shipping_area_id == false) {
            // 如果市和省份都没查到, 就查询 tp_shipping_area 表 is_default = 1 的  表示全国的  select * from `tp_plugin`  select * from  `tp_shipping_area` select * from  `tp_area_region`
            $shipping_area_id = ShippingArea::where(['shipping_id'=>$shipping_code,'is_default'=>1])->column('shipping_area_id');
        }

        if ($shipping_area_id == false) {
            return 0;
        }

        /// 找到了 shipping_area_id  找config
        $shipping_config = ShippingArea::field('config')->where("shipping_area_id",'in',$shipping_area_id)->find();

        $shipping_config = unserialize($shipping_config['config']);
        $shipping_config['money'] = $shipping_config['money'] ? $shipping_config['money'] : 0;
        // 1000 克以内的 只算个首重费
        if ($weight < $shipping_config['first_weight']) {
            return $shipping_config['money'];
        }
        // 超过 1000 克的计算方法
        $weight = $weight - $shipping_config['first_weight']; // 续重
        $weight = ceil($weight / $shipping_config['second_weight']); // 续重不够取整
        $freight = $shipping_config['money'] + $weight * $shipping_config['add_money']; // 首重 + 续重 * 续重费
        return $freight;
    }
}


?>